package logic

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"math/rand"
	"produce/model/redis"
	"produce/pkg"
	"produce/producerpc/internal/svc"
	"produce/producerpc/producerpc"
	"strconv"
	"time"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *producerpc.SendSmsRequest) (*producerpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line

	sendsmslist := redis.Client.Get("sendsmslist" + in.Tel + in.Source)
	if sendsmslist.Val() >= "5" {
		return nil, fmt.Errorf("短信最多发送5次/小时")
	}

	Intn := rand.Intn(9000) + 1000
	sms, err := pkg.SendSms(in.Tel, strconv.Itoa(Intn))
	if err != nil {
		return nil, err
	}
	if *sms.Body.Code != "OK" {
		return nil, fmt.Errorf(*sms.Body.Message)
	}

	redis.Client.Set("sendsms"+in.Tel+in.Source, Intn, time.Minute*10)

	incr := redis.Client.Incr("sendsmslist" + in.Tel + in.Source)
	if incr.Val() >= 5 {
		redis.Client.Expire("sendsmslist"+in.Tel+in.Source, time.Hour)
	}

	return &producerpc.SendSmsResponse{}, nil
}
